package courier;

import entity.CommentsLocalHome;
import entity.CommodityLocal;
import entity.CommodityLocalHome;
import entity.OrdersLocal;
import entity.OrdersLocalHome;
import helper.SimpleJSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import transfer.Comment;
import transfer.Commodity;
import transfer.Order;
import transfer.OrderState;

/**
 *
 * @author Oleh, Sergey
 */
public class Courier extends HttpServlet {

    public static final String answer = "answer";
    public static final String ok = "OK";
    public static final String wrong = "WRONG";
    public static final String idParameter = "id";
    public static final String commentParameter = "comment";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer id = Integer.valueOf(request.getParameter(idParameter));
        String commentString = request.getParameter(commentParameter);
        System.out.println("id = " + id);
        System.out.println("comment = " + commentString);
        SimpleJSONObject json = new SimpleJSONObject();
        try {
            InitialContext context = new InitialContext();
            OrdersLocalHome homeOrder = (OrdersLocalHome) context.lookup("java:comp/env/Orders");
            OrdersLocal localOrder = homeOrder.findByPrimaryKey(id);
            Order order = localOrder.getOrder();
            if (order.getOrderState().equals(OrderState.SHIPPING)) {
                order.setOrderState(OrderState.DELIVERED);
                Date deliveredDate = new Date();
                order.setDeliveredDate(deliveredDate);
                HashMap map = order.getCommodities();
                Set keys = map.keySet();
                CommodityLocalHome commodityHome = (CommodityLocalHome) context.lookup("java:comp/env/Commodity");
                for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
                    Commodity commodity = (Commodity) iterator.next();
                    Integer quantity = (Integer) map.get(commodity);
                    Integer popularity = commodity.getPopularity();
                    if (popularity == null) {
                        popularity = new Integer(0);
                    }
                    popularity = new Integer(popularity.intValue() + quantity.intValue());
                    commodity.setPopularity(popularity);
                    CommodityLocal commodityLocal = commodityHome.findByPrimaryKey(commodity.getIdCommodity());
                    commodityLocal.setCommodity(commodity);
                }
                if (commentString != null && !commentString.equals("")) {
                    CommentsLocalHome homeComment = (CommentsLocalHome) context.lookup("java:comp/env/Comments");
                    Comment comment = new Comment();
                    comment.setCommentText(commentString);
                    comment.setOrder(order);
                    comment.setOrderState(order.getOrderState());
                    comment.setUser(order.getCourier());
                    comment.setCommentDate(deliveredDate);
                    homeComment.create(comment);
                }
                localOrder.setOrder(order);
                json.addProperty(answer, ok);
            }
        } catch (NamingException ex) {
            ex.printStackTrace();
            json.addProperty(answer, wrong);
        } catch (FinderException ex) {
            ex.printStackTrace();
            json.addProperty(answer, wrong);
        } catch (CreateException ex) {
            ex.printStackTrace();
            json.addProperty(answer, wrong);
        }
        sendJSON(json, response);
    }

    private void sendJSON(SimpleJSONObject json, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(json);
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
